package com.tool4j.util;

import com.tool4j.common.EnvEnum;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

/**
 * @author Deng.Weiping
 * @since 2023/8/7 8:41
 */
@Component
public class SpringUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    public void setApplicationContext(ApplicationContext context) {
        applicationContext = context;
    }

    public static <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }

    /**
     * 获取当前运行环境
     */
    public static String getEnv() {
        Environment environment = applicationContext.getEnvironment();
        String[] activeProfiles = environment.getActiveProfiles();
        if (activeProfiles == null || activeProfiles.length == 0) {
            return null;
        }
        return activeProfiles[0];
    }

    /**
     * 是否是开发环境
     *
     * @return
     */
    public static boolean isDev() {
        String activeProfile = getEnv();
        if (activeProfile == null) {
            return false;
        }
        return EnvEnum.LOCAL.getValue().equals(activeProfile)
                || EnvEnum.DEV.getValue().equals(activeProfile);
    }
}